package com.heima.article.service.impl;

import com.heima.article.service.ArticleLoadBehaviorService;
import com.heima.common.constans.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.ArticleLoadBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jsoup.helper.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ArticleLoadBehaviorServiceImpl implements ArticleLoadBehaviorService {
    /**
     * 回显文章行为
     * @param dto
     * @return
     */
    @Autowired
    private CacheService cacheService;
    @Override
    public ResponseResult loadArticleBehavior(ArticleLoadBehaviorDto dto) {
        //1.校验参数
        if (dto == null || dto.getArticleId() == null || dto.getAuthorId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查看是否登录
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.回显文章详情 "islike":false,"isunlike":false,"iscollection":false,"isfollow":falses
        boolean isUnLike = false,isLike = false,isCollection = false,isFollow = false;
        String unLikeBehaviorJson = (String) cacheService.hGet(BehaviorConstants.UN_LIKE_BEHAVIOR + dto.getArticleId(), user.getId().toString());
        if (StringUtils.isNotBlank(unLikeBehaviorJson)){
            isUnLike = true;
        }
        String LikeBehaviorJson = (String) cacheService.hGet(BehaviorConstants.LIKE_BEHAVIOR + dto.getArticleId(), user.getId().toString());
        if (StringUtils.isNotBlank(LikeBehaviorJson)){
            isLike = true;
        }
        String collectBehaviorJson = (String) cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + dto.getArticleId(), user.getId().toString());
        if (StringUtils.isNotBlank(collectBehaviorJson)){
            isCollection = true;
        }
        Double followScore = cacheService.zScore(BehaviorConstants.APUSER_FOLLOW_RELATION + user.getId(), dto.getAuthorId().toString());
        if (followScore != null){
            isFollow = true;
        }
        Map<String,Boolean> map = new HashMap<>();
        map.put("islike",isLike);
        map.put("isunlike",isUnLike);
        map.put("iscollection",isCollection);
        map.put("isfollow",isFollow);
        return ResponseResult.okResult(map);
    }
}
